﻿-- =============================================
-- Author:		David Settino
-- Create date: 01/03/2011
-- Description:	Converts a circle of a given radius
--    around a geographic point to a polygon
-- =============================================

CREATE FUNCTION [dbo].[CircleToPolygon](@circle varchar)
RETURNS geography
AS
BEGIN
  DECLARE @index int
  DECLARE @pointstr VARCHAR(50)
  DECLARE @radius int
  DECLARE @lat decimal(18,5)
  DECLARE @lon decimal(18,5)
  DECLARE @Polygon [geography]
  SET @index = CHARINDEX(' ', @Circle)
  SET @radius = SUBSTRING(@Circle, @index+1, LEN(@Circle)-@index)
  SET @pointstr = SUBSTRING(@Circle, 0, @index-1)
  SET @radius = @radius * 1000
  SET @index = CHARINDEX(',', @pointstr)
  SET @lat = CAST(SUBSTRING(@pointstr,0, @index-1) AS DECIMAL)
  SET @lon = CAST(SUBSTRING(@pointstr, @index+1, LEN(@pointstr)-@index) AS DECIMAL)
  SET @Polygon = geography::Point(@Lat,@Lon,4326).STBuffer(@Radius)
  RETURN @Polygon
END